package main

import (
	"net"
	"fmt"
	"github.com/google/gopacket/layers"
	"github.com/google/gopacket"
)

func main() {
	protocol := "icmp"
	netaddr, _ := net.ResolveIPAddr("ip4", "127.0.0.1")
	conn, _ := net.ListenIP("ip4:"+protocol, netaddr)

	buf := make([]byte, 1024)
	numRead, _, _ := conn.ReadFrom(buf)
	//open terminal, send cmd: ping 127.0.0.1
	fmt.Printf("% X\n", buf[:numRead])

	/*我是分割线, gopacket 解析ICMP packet*/
	var icmpv4 layers.ICMPv4
	decoded := []gopacket.LayerType{}
	parser := gopacket.NewDecodingLayerParser(layers.LayerTypeICMPv4, &icmpv4)
	parser.DecodeLayers(buf[:numRead], &decoded)
	for _, layerType := range decoded {
		switch layerType {
		case layers.LayerTypeICMPv4:
			fmt.Printf("    icmpv4: typecode->%s,Seq->%x,Checksum->%d,id->%d,Contents:%b", icmpv4.TypeCode.String(), icmpv4.Seq, icmpv4.Checksum, icmpv4.Id, icmpv4.Contents)
		}
	}

	/*08 00 61 68 5B 9B 00 01 7D D0 C5 59 00 00 00 00 38 FE 00 00 00 00 00 00 10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F 20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F 30 31 32 33 34 35 36 37
icmpv4: typecode->EchoRequest,Seq->1,Checksum->24936,id->23451,Contents:[1000 0 1100001 1101000 1011011 10011011 0 1]*/

}
